package com.rookie.im.core.server.utils;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;

import com.rookie.im.core.config.AppConfig;

import lombok.Getter;

public class RedisManager {
	private static final Object lock = new Object();
	@Getter
	private static volatile RedissonClient redissonClient;
	
	public static void init(AppConfig.RedisConfig redisConfig) {

		if (redissonClient == null) {
			synchronized (lock) {
				Config config = new Config();
				String node = redisConfig.getSingle().getAddress();
				if (!node.startsWith("redis://")) {
					node = "redis://" + node; 
				}
				SingleServerConfig singleServerConfig = config.useSingleServer()
					.setAddress(node)
					.setDatabase(redisConfig.getDatabase())
					.setTimeout(redisConfig.getTimeout())
					.setConnectTimeout(redisConfig.getPoolConnTimeout())
					.setConnectionMinimumIdleSize(redisConfig.getPoolMinIdle())
					.setConnectionPoolSize(redisConfig.getPoolSize());
				String password = redisConfig.getPassword();
				if (password != null && !password.isEmpty()) {
					singleServerConfig.setPassword(password);
				}
				config.setCodec(new StringCodec());
				redissonClient = Redisson.create(config);
			}
		}
	}
}
